package com.yuma.lock;

import java.util.concurrent.locks.ReentrantLock;

class Ticket{

    private final ReentrantLock lock = new ReentrantLock(true);

    //  定义一个票数
    private int number = 100;

    //  定义一个卖票的方法:
    public void sale(){

        lock.lock();

        //  判断
        if (number<=0){
            System.out.println(Thread.currentThread().getName() + "票已售罄！");
            lock.unlock();
            return;
        }

        try {
            System.out.println(Thread.currentThread().getName() + "开始买票，当前票数：" + number);
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + "买票结束，剩余票数：" + --number);

            // 调用check方法测试锁的可重入性
            // check();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 为了测试可重入锁，添加检查余票方法
     */
    public void check(){
        lock.lock();
        System.out.println("检查余票。。。。");
        lock.unlock();
    }
}
public class FairLock {
    public static void main(String[] args) {

        Ticket ticket = new Ticket();

        Thread t1 = new Thread(()->{
            for(int i = 0; i < 10; i++){
                ticket.sale();
            }
        },"A");

        Thread t2 = new Thread(()->{
            for(int i = 0; i < 10; i++){
                ticket.sale();
            }
        },"B");

        Thread t3 = new Thread(()->{
            for(int i = 0; i < 10; i++){
                ticket.sale();
            }
        },"C");

        t1.start();
        t2.start();
        t3.start();
    }
}
